import Taro from '@tarojs/taro';
import {Image, View, Button} from '@tarojs/components';
import {AtList, AtListItem} from "taro-ui";
import {connect} from "@tarojs/redux";
import {actionCreator} from "../../store/actions";
import Modal from '../../components/modal/Modal';
import PhoneModal from  '../../components/phone-modal/phoneModal';
import {appConfig, request, unite} from '../../utils/index';
import './my.scss';
import head from '../../asset/images/head.png';
import Zuan from "../../asset/images/zuan.png";
import Close from "../../asset/images/close.png";
import Right from "../../asset/myImages/right.png";
import UnionidModal from "../../components/unionid-modal/unionidModal";

class Mall extends Taro.Component {
    config = {
        navigationBarTitleText: '个人中心',
        navigationBarBackgroundColor: '#F6F7F7',
        enablePullDownRefresh: true
    };

    state = {
        unionId: false, //获取用户信息弹窗
        phoneId: false, // 0 未授权手机号
        modalStatus: false,
        userData: [], //用户信息
        mealStatus: false, //套餐购买弹窗
        mealData: [],
        couponList: [], //优惠券列表
    };

    componentDidShow(){
        const {mobileFlag, existUser} = this.props;
        if (existUser == 0) { //未授权用户信息
            this.setState({
                unionId: true
            });
            return;
        }
        if (mobileFlag == 0) { //未授权手机号
            this.setState({
                phoneId: true
            });
            return;
        }
        this.init(); //获取用户信息
        this.getCoupon();
    }

    //获取用户信息
    init = () => {
        const params = {
            url: '/wx/firstPage/getUserDetail',
            data:{}
        };
        request(params).then(res => {
            Taro.stopPullDownRefresh();
            if (res) {
                if(res.code == 200) {
                    if (res && res.data) {
                        this.setState({
                            userData: res.data,
                        })
                    }
                }
            }
        })
    };

    //获取套餐列表
    getCoupon = () => {
        const params = {
            url: '/wx/packages/listPackages',
            data:{}
        };
        request(params).then(res => {
            Taro.stopPullDownRefresh(); //停止当前页面下拉刷新
            if (res) {
                if(res.code == 200) {
                    if (res && res.data) {
                        this.setState({
                            couponList: res.data,
                        })
                    }
                }
            }
        })
    };

    //跳转我的收藏
    skipHelpCenter = () => {
        Taro.navigateTo({
            url: './my-take/myTake'
        })
    };

    //跳转我的优惠卷
    skipCoupon = () => {
        Taro.navigateTo({
            url: './my-coupon/myCoupon'
        })
    };

    tanchuanModel = () => {
        this.setState(PrevState => ({
            modalStatus: !PrevState.modalStatus
        }))
    };

    //拨打电话
    confirmPhone = () => {
        this.setState({
            modalStatus: false
        }, () => {
            Taro.makePhoneCall({
                phoneNumber: '186-8738-0398',
                success:() => {
                    console.log("拨打电话成功！")
                },
                fail:() => {
                    console.log("拨打电话失败！")
                }
            })
        })
    };

    //转发
    onShareAppMessage = () => {
        return {
            title: '健身APP',
            path: 'pages/index/index'
        }
    };

    //教练排课
    skipMyTrain = () => {
        const {userData} = this.state;
        if (userData.coachFlag == 1) { //1教练申请中
            Taro.navigateTo({
                url: './my-train-none/myTrainNone'
            })
        } else if (userData.coachFlag == 4) { //教练停用
            unite.showTipModal('该教练已被停用');
        } else {
            Taro.navigateTo({
                url: './my-train/myTrain?coachFlag='+userData.coachFlag + '&avatar=' + userData.avatar //0 普通用户、1教练申请中、 2教练审请通过、3教练申请未通过
            })
        }
    };

    //教室排课
    skipmyClassroom = () => {
        const {userData} = this.state;
        if (userData.hasAccessRoom == 'Y') {
            Taro.navigateTo({
                url: './my-classroom/myClassroom?avatar=' + userData.avatar
            })
        } else {
            unite.showToast('您的门店暂未开放');
        }
    };

    //购买套餐
    paySetMeal = (item) => {
        this.setState(prevState => ({
            mealData: item ? item : [],
            mealStatus: !prevState.mealStatus,
        }))
    };

    //我的动静
    skipMyDynamic = () => {
        Taro.navigateTo({
            url: './my-dynamic/myDynamic'
        })
    };

    //微信支付购买套餐
    sumbit = () => {
        const {mealData} = this.state;
        this.paySetMeal();
        const params = {
            url: '/wx/packages/pay',
            data:{
                packageId: mealData.packageId,
            }
        };
        request(params).then(res => {
            if (res) {
                if(res.code == 200) {
                    if (res) {
                        this.onMiniPay(res);
                    }
                }
            }
        })
    };

    //小程序支付
    onMiniPay = info => {
        Taro.requestPayment({
            timeStamp: info.data.timeStamp.toString(),
            nonceStr: info.data.nonceStr,
            package: info.data.packageValue,
            signType: info.data.signType,
            paySign: info.data.paySign,
            success: () => {
                unite.showToast('购买成功');
                this.init();
            },
            fail: () => {
                unite.showToast('支付失败');
                console.log('支付失败');
            },
        });
    };

    //判断是否需要获取用户信息
    userInfoModel = () => {
        const {userData} = this.state;
        this.setState({
            unionId: true, //打开授权弹窗
        })
        if (userData.getUserInfo == 'N') { //未授权

        }
    };

    unGetUserInfo = (is) => {
        const {mobileFlag, setExistUser} = this.props;
        if (is) {
            setExistUser(1);
            this.setState({
                phoneId: mobileFlag == 0 ? true : false
            });
            this.init();
        } else {
            Taro.switchTab({
                url: `/pages/index/index`
            })
        }
        this.setState({
            unionId: false, //关闭 nu ni id 弹窗
        });
    };

    //授权手机号
    unGetPhone = (is) => {
        const {setMobileFlag} = this.props;
        if (is) {
            setMobileFlag(1);
            this.init(); //获取用户信息
            this.getCoupon();
        } else {
            Taro.switchTab({
                url: `/pages/index/index`
            })
        }
        this.setState({
            phoneId: false, //关闭弹窗
        });
    };

    // 下拉刷新
    onPullDownRefresh = () => {
        this.init();
    };

    render() {
        const {modalStatus, userData, mealStatus, couponList, mealData, phoneId, unionId} = this.state;
        return (
            <View className="page">
                <View className="page-head">
                    <View className="page-head-wrap flex-top" onClick={this.userInfoModel}>
                        <View className="page-head-title">
                            <View className="flex-l head-name">
                                <View>{userData.nickname}</View>
                                <View className="grade flex-center">
                                    <Image className="imgs" src={Zuan} mode="aspectFit"/>
                                    <View>{userData.vipName}</View>
                                </View>
                            </View>
                            <View>ID：{userData.userShowId}</View>
                        </View>
                        <Image className="page-head-img" src={userData.avatar || head}/>
                    </View>
                    <View className="price-wrap flex-l">
                        <View className="next-num" onClick={() => {Taro.navigateTo({url: './my-balance/myBalance?price=' + userData.accountBalance})}}>
                            <View className="number text-overflow">¥{userData.accountBalance}</View>
                            <View>余额</View>
                        </View>
                        <View className="next-num" onClick={this.skipCoupon}>
                            <View className="number text-overflow">{userData.couponNum}张</View>
                            <View>优惠券</View>
                        </View>
                    </View>
                </View>
                <View className="youhuiquan">
                    {couponList && couponList.map((item, index) => (
                        //onClick={this.paySetMeal.bind(this, item)}
                        <View className="yhq-item flex-bottom" key={index} onClick={() => {Taro.navigateTo({url: './meal-list/mealList?packageId=' + item.packageId+ '&phoneId=' + phoneId})}}>
                            <View className="item-left-text">
                                <View className="flex-l price">
                                    <View className="price-nums">¥{item.factAcceptCharge}</View>
                                    <View>（到账¥{item.chargeTotal}）</View>
                                </View>
                                <View>{item.couponDesc}</View>
                            </View>
                            <View className="titles">{item.description}</View>
                            <View className="set-meal flex-center">套餐</View>
                        </View>
                    ))}
                    <View className="yhq-item yhq-item-list flex-center" onClick={() => {Taro.navigateTo({url: './meal-list/mealList?phoneId=' + phoneId})}}>
                        <View>
                            <View>更多套餐</View>
                            <Image className="imgs-yhq" src={Right} mode="aspectFit"/>
                        </View>
                    </View>
                </View>
                {/*列表*/}
                <View className="list-content">
                    <View className="list-black">
                        <View className="list">
                            <View className="list-black-fenxaing"  onClick={this.skipHelpCenter}>
                                <Button className="fenxaing-btn">我的收藏</Button>
                                <View className="arrow"></View>
                            </View>
                            <View className="list-black-fenxaing borderTop" onClick={this.skipMyDynamic}>
                                <Button className="fenxaing-btn">我的动态</Button>
                                <View className="arrow"></View>
                            </View>
                        </View>
                    </View>
                    {/*<View className="list-black">*/}
                    {/*    <View className="list">*/}
                    {/*        <View className="list-black-fenxaing" onClick={this.tanchuanModel}>*/}
                    {/*            <Button className="fenxaing-btn">我的客服</Button>*/}
                    {/*            <View className="arrow"></View>*/}
                    {/*        </View>*/}
                    {/*        <View className="list-black-fenxaing borderTop">*/}
                    {/*            <Button openType="share" className="fenxaing-btn">邀请有礼</Button>*/}
                    {/*            <View className="arrow"></View>*/}
                    {/*        </View>*/}
                    {/*    </View>*/}
                    {/*</View>*/}
                    <View className="list-black list-black-next">
                        <View className="list">
                            <View className="list-black-fenxaing" onClick={this.skipMyTrain}>
                                <Button className="fenxaing-btn">{userData.coachFlag == 2 ? '教练中心' : '教练入驻'}</Button>
                                <View className="arrow"></View>
                            </View>
                            <View className="list-black-fenxaing borderTop" onClick={this.skipmyClassroom}>
                                <Button className="fenxaing-btn">{userData.hasAccessRoom == 'Y' ? '门店中心' : '门店入驻'}</Button>
                                <View className="arrow"></View>
                            </View>
                            <Button className="fenxaing-btn" open-type="contact">
                                <View className="list-black-fenxaing borderTop">
                                    <View className="fenxaing-btn">我的客服</View>
                                    <View className="arrow"></View>
                                </View>
                            </Button>
                            {/*<View className="list-black-fenxaing borderTop">*/}
                            {/*    <Button className="fenxaing-btn">联系我们</Button>*/}
                            {/*    <View className="arrow"></View>*/}
                            {/*</View>*/}
                        </View>
                    </View>
                </View>
                { modalStatus &&(
                    <Modal messageText='187-4894-0024' onCancel={this.tanchuanModel} onConfirm={this.confirmPhone} confirmText='拨打'/>
                )}
                {/*获取用户信息*/}
                {unionId &&(
                    <UnionidModal onCancel={this.unGetUserInfo}/>
                )}
                {phoneId &&(
                    <PhoneModal onCancel={this.unGetPhone}/>
                )}
                {/*    购买套餐弹窗*/}
                {mealStatus && (
                    <View className="model-type flex-bottom">
                        <View className="set-meal-content">
                            <View className="meal-names">
                                <View>购买套餐</View>
                                <Image className="img-close" src={Close} onClick={this.paySetMeal} mode="aspectFit"/>
                            </View>
                            <View className="meal-list-wrap">
                                <View className="meal-list flex-lr">
                                    <View>套餐名称</View>
                                    <View className="name">{mealData.packageName}</View>
                                </View>
                                <View className="meal-list flex-lr">
                                    <View>到账</View>
                                    <View className="name">{mealData.chargeTotal}元</View>
                                </View>
                                <View className="meal-list meal-list-none flex-lr">
                                    <View>优惠券</View>
                                    <View className="name">{mealData.couponDesc}</View>
                                </View>
                            </View>
                            <View className="prompt-text">7天无条件退款，余额可补差价使用</View>
                            <View className="max-btn flex-center" onClick={this.sumbit}>微信支付 ¥{mealData.factAcceptCharge}</View>
                        </View>
                    </View>
                )}
            </View>
        )
    }
}

const mapStateToProps = state => {
    let {userToken, mobileFlag, existUser} = state;
    return {
        userToken,
        mobileFlag,
        existUser
    }
};

const mapDispatchToProps = {
    setUserToken: actionCreator.setUserToken,
    setExistUser: actionCreator.setExistUser,
    setMobileFlag: actionCreator.setMobileFlag,
};

export default connect(mapStateToProps, mapDispatchToProps)(Mall);
